<!DOCTYPE html>
<html lang="en">

<head>
 <meta charset="UTF-8">
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <title>HTML5 直播推流</title>
 <style>
  video {
   width: 500px;
   height: 300px;
  }

  .parent {
   position: relative;
  }

  .parent #recordButton {
   position: absolute;
   z-index: 3;
   top: 50%;
   left: 170px;
   width: 100px;
   transform: translate(0%, -50%);
  }

  .canvas {
   position: absolute;
   z-index: 1;
   top: 20px;
   left: 0;
   width: 100%;
   height: 100%;
   opacity: 0.8;
   background-color: #fff;
   pointer-events: none;
  }

  .button {
   padding: 10px;
   background-color: #007bff;
   border-radius: 5px;
   color: #fff;
   border-color: #fff;
   cursor: pointer;
  }

  .between {
   display: flex;
   justify-content: space-between;
  }
 </style>
</head>

<body>

 <div class="between">
  <div class="parent">
   <div>用户录制直播</div>
   <div class="canvas"></div>
   <div id="recordButton">
    <div class="button">开始录制</div>
   </div>
   <video id="localVideo" controls autoplay playsinline></video>
   <button id="stopButton">关闭直播</button>
  </div>
  <div class="parent">
   <div>用户查看直播</div>
   <div class="canvas"></div>
   <div id="recordButton">
   </div>
   <video id="localVideo" controls autoplay playsinline></video>
  </div>
 </div>
 <script src="https://unpkg.com/socket.io-client@4.8.1/dist/socket.io.js"></script>
 <script>
  let mediaRecorder, stream
  let btn = document.querySelector('.button');
  let canvas = document.querySelector('.canvas');
  const localVideo = document.getElementById('localVideo');
  const closeButton = document.getElementById('stopButton'); // 获取关闭直播按钮
  let socket = io("http://localhost:8000")

  // 监听开始录制按钮的点击事件
  btn.addEventListener('click', () => {
   startStreaming();
  })
  // 监听关闭直播按钮的点击事件
  closeButton.addEventListener('click', (e) => {

   // 在这里执行关闭直播的逻辑，例如发送关闭直播请求到服务器
   // 示例代码省略，实际开发中需要实现这部分逻辑
   if (localVideo.srcObject || stream) {
    const tracks = stream.getTracks();
    tracks.forEach(track => track.stop());
    localVideo.srcObject = null;
   }
   mediaRecorder.stop();
   btn.setAttribute("style","display:block;");
   canvas.setAttribute("style","display:block;");
  });

  async function startStreaming () {
   try {
    await navigator.mediaDevices.getUserMedia({ video: true, audio: true })
     .then(st => {
      stream = st;
      const options = { mimeType: 'video/webm;codecs=vp9' };
      mediaRecorder = new MediaRecorder(st, options);
      canvas.setAttribute("style","display:none;");
      btn.setAttribute("style","display:none;");
     })
     .catch(error => {
      console.error('无法访问摄像头:', error);
     });
    localVideo.srcObject = stream;

    // 这里应该添加 WebRTC 代码来将流发送到流媒体服务器
    // 示例代码省略，以下是一个简单的 WebRTC 连接框架

    // 创建 RTCPeerConnection
    const pc = new RTCPeerConnection();
    stream.getTracks().forEach(track => pc.addTrack(track, stream));

    // 创建 启动与远程对等方的新 WebRTC 连接
    pc.createOffer({offerToReceiveAudio:1,offerToReceiveVideo:1}).then(offer => pc.setLocalDescription(offer))
     .then(() => fetch('http://localhost:8000/chat-video/test', {
      method: 'POST',
      body: JSON.stringify({ sdp: pc.localDescription }),
      headers: { 'Content-Type': 'application/json' }
     }))
     .then(response => {
      console.log("response====>");
      response.json()
     })
     // .then(answer => pc.setRemoteDescription(new RTCSessionDescription(answer)))
     .then(() => { 
      console.log('WebRTC 连接已建立'); 
     })
     .catch(error => console.error('Error creating offer:', error));
     
     // 监听 ICE 候选并发送到服务器
     pc.onicecandidate = event => {
      if (event.candidate) {
       fetch('http://localhost:8000/chat-video/test', {
        method: 'POST',
        body: JSON.stringify({ candidate: event.candidate }),
        headers: { 'Content-Type': 'application/json' }
       });
      }
     };

    // 监听来自服务器的 SDP 答复和 ICE 候选
    // 并设置远程描述和添加 ICE 候选
    // 示例代码省略，实际开发中需要实现这部分逻辑

   } catch (error) {
    console.error('Error accessing media devices.', error);
   }
  }
 </script>
</body>

</html>